/*
 * @Author: 蔡继周
 * @Date: 2021-11-12 09:14:21
 * @LastEditTime : 2021-12-08 15:28:27
 * @LastEditors  : Shaquille.Cai
 * @Description: utils
 */



/**
 * @description:  置空一个对象
 * @param {*}
 * @return {*}
 */
const clearObj = (object) => {
        const obj = {...object }
        Object.keys(obj).forEach(key => {
            if (Array.isArray(obj[key])) {
                obj[key] = []
            }
            if (typeof obj[key] === 'number' && !isNaN(obj[key])) {
                obj[key] = null
            }
            if (typeof(obj[key]) === 'string') {
                obj[key] = null
            }
            if (Object.prototype.toString.call(obj[key]) === '[object Object]') {
                obj[key] = clearObj(obj[key])
            }
            if (typeof(obj[key]) === 'boolean') {
                obj[key] = false
            }
        })
        return obj
    }
/**
 * @description: 扁平化数据转为树形结构
 * @param {*}
 * @return {*}
 */    
const FlatToTree = (arr, pidStr = 'parent_id', idStr = 'id', childrenStr = 'children') => {
    let temp = {} //扁平数组转对象 key是id  value是数组中id所对应的对象
    let tree = [] //最终数组
    for (let index = 0; index < arr.length; index++) {
        temp[arr[index][idStr]] = arr[index]
    }
    for (let key = 0; key < arr.length; key++) {
        //temp中 是否有对应的父级数据
        const parentNode = temp[arr[key][pidStr]]
        if (parentNode) {
            // 如果有父级数据，则在父级数据中建立children字段
            !parentNode[childrenStr] && (parentNode[childrenStr] = [])
                //  将当前数据插入到父级数据的children中            
            parentNode[childrenStr].push(arr[key])
        } else {
            // 如果没有直接插入
            tree.push(arr[key])
        }
    }
    return tree
}

const resetZero = (data) => {
    if (data===0) {
        return true
    }
    return !!data
}

export {
    clearObj,
    FlatToTree,
    resetZero
}